import { isFunction } from '@/utils'

interface SubmitProps {
  msg?: string | Ref<string>
  apikey?: ComputedRef<string> | string
  hooks?: {
    onSuccess: Function
  }
}
export function useBaseSubmit({
  msg = '',
  apikey = '',
  hooks,
}: SubmitProps) {
  const loading = useLoading()
  const bvisible = ref(false)

  function bdisplay() {
    bvisible.value = true
  }
  const message = toRef(msg)
  async function bsubmit(params) {
    loading.open()

    if (!apikey) {
      ElNotification({
        type: 'error',
        message: `未找到【${msg}】请求接口`,
      })
      loading.close()
      return
    }
    const api = toValue(apikey)
    if (!api) {
      ElNotification({
        type: 'error',
        message: `未找到请求接口`,
      })
      loading.close()
      return
    }
    const result = await useRequest(api, params) as { success: boolean }
    loading.close()
    if (result.success) {
      ElNotification({
        type: 'success',
        message: `${message.value}成功`,
      })
      bvisible.value = false

      hooks.onSuccess()
    }
  }
  return {
    message,
    bvisible,
    bdisplay,
    bsubmit,
  }
}
